import keyboard
import pyaudio
import sys,os
import time
import zmq
from threading import Thread, current_thread
def target01():
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://localhost:5555")
    string_to_send = "is ok?"
    
    while True:
        print(f"sending {string_to_send}")
        socket.send(string_to_send.encode())
        num = socket.poll(1000)
        if num == 0:
            exit_flag = True
            os._exit(0)
        message = socket.recv()
        # print(f"reversed: {message}")
        time.sleep(3)
 

# 创建线程
thread01 = Thread(target=target01)
# 启动线程
thread01.start() 


def toggleflag(e):
    global flag
    flag = not flag
    if flag :
        print("Streaming audio (press Ctrl+C to stop)...")
    else:
        print("Stopped streaming audio")
        
        



flag = False
p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
num_devices = info.get('deviceCount')
input_device_index = pyaudio.PyAudio().get_default_input_device_info()['index']
output_device_index = pyaudio.PyAudio().get_default_output_device_info()['index']
print("Available audio devices:")
for i in range(0, num_devices):
    device = p.get_device_info_by_host_api_device_index(0, i)
    # print(f"Device {i}: {device['name']}")
    if device["name"].find("CABLE Input") != -1:
        output_device_index = i

# input_device_index = int(input("Enter the input device index: "))
# output_device_index = int(input("Enter the output device index: "))

print(input_device_index)
print(output_device_index)
stream = p.open(format=pyaudio.paInt16,
                channels=2,
                rate=44100,
                input=True,
                output=True,
                input_device_index=input_device_index,
                output_device_index=output_device_index)
keyboard.on_press_key("`", toggleflag)
try:
    while True:
        if flag: 
            
            data = stream.read(1024)
            print(data)
            stream.write(data)
        else:
            time.sleep(1)
except KeyboardInterrupt:
    pass
        
stream.stop_stream()
stream.close()
p.terminate()
